<script setup lang="ts">
import {
  TreeNodeData,
  TreeKey,
  TreeData
} from "element-plus/es/components/tree/src/tree.type.mjs";
import { computed, reactive, ref, watch } from "vue";

type Pagination = {
  pageSize: number;
  pageNum: number;
};

const props = defineProps<{
  checkable?: boolean;
  expandAll?: boolean;
  valueField?: string;
  labelField?: string;
  childrenField?: string;
  data?: any[];
  checkedKeys?: any[];
  getDataList: (params: Pagination) => Promise<{ list: any[]; total: number }>;
  filterFunc?: (query: string, data: any) => boolean;
}>();

const dataList = ref<any[]>([]);
const loading = ref(false);
const treeRef = ref();
const emit = defineEmits(["update:checkedKeys"]);

const onCheckKeyChange = (
  data: TreeNodeData,
  info: {
    checkedKeys: TreeKey[];
    checkedNodes: TreeData;
    halfCheckedKeys: TreeKey[];
    halfCheckedNodes: TreeData;
  }
) => {
  emit("update:checkedKeys", info?.checkedKeys || []);
};

watch(
  () => props.data,
  val => {
    if (val) {
      dataList.value = val;
    }
  },
  { immediate: true }
);

defineExpose({
  getCheckedKeys() {
    return treeRef.value.getCheckedKeys();
  }
});
</script>

<template>
  <el-tree-v2
    ref="treeRef"
    v-loading="loading"
    :data="dataList"
    :default-checked-keys="checkedKeys"
    :props="{
      children: props.childrenField || 'children',
      label: props.labelField || 'name',
      value: props.valueField || 'id'
    }"
    :show-checkbox="checkable"
    :filter-method="filterFunc"
    expand-on-click-node
    @check="onCheckKeyChange"
  />
</template>
<style lang="scss" scoped></style>
